<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import { searchGoods, searchPurGoods } from '#/api/backend/printCareLabel'
import { Card, Button, Table, Input, Form, FormItem, Row, Col } from 'ant-design-vue'
import { AntPlusOutlined, createIconifyIcon } from '@vben/icons'
import PrintPreview from './modules/printPreview.vue'

const AntPrinterOutlined = createIconifyIcon('ant-design:printer-outlined')


/**
 * 打印模板配置
 */
const printTemplates = [
  { key: 'templateA', name: '水洗唛裤子内搭专用(13cm X 4cm)' },
  { key: 'templateB', name: '水洗唛裤子内搭专用(编码)' },
  { key: 'templateC', name: '水洗唛外套' },
  { key: 'templateD', name: '针织秋季专用洗水唛模版（不可熨烫）' },
  { key: 'templateE', name: '水洗唛裤子内搭专用(编码)(水洗产品)' },
]

// 选中的模板
const selectedTemplate = ref<any>(null)
const selectedTemplateIndex = ref(0)


/**
 * 选择模板
 */
const handleSelectTemplate = (template: any, index: number) => {
  selectedTemplate.value = template
  selectedTemplateIndex.value = index
}

/**
 * 货品搜索筛选
 */
const searchForm = reactive({
  purchase_sn: '',
  goods_no: '',
  template_no: '',
})
const sourceGoodsTableData = ref<any[]>([])
const sourceGoodsLoading = ref(false)
const sourceGoodsPagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 货品来源表格列定义
const sourceGoodsColumns = [
  {
    title: '图片',
    dataIndex: 'template_images',
    width: 80,
    cellRender: {name:'CellImage'},
  },
  {
    title: '采购单',
    dataIndex: 'goods_purchase_sn',
    width: 160,
    fixed: 'left' as const,
  },
  {
    title: '货号',
    dataIndex: 'goods_no',
    width: 160,
    fixed: 'left' as const,
  },
  {
    title: '采购类型',
    dataIndex: 'purchase_type_name',
    width: 100,
  },
  {
    title: '简码',
    dataIndex: 'template_no',
    width: 140,
  },
  {
    title: '品名',
    dataIndex: 'goods_name',
    width: 140,
  },
  {
    title: '颜色',
    dataIndex: 'color_name',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right' as const,
  },
]

/**
 * 加载货品列表
 */
const loadSourceGoods = async () => {
  sourceGoodsLoading.value = true
  try {
    const res = await searchPurGoods({
      purchase_sn: searchForm.purchase_sn,
      goods_no: searchForm.goods_no,
      template_no: searchForm.template_no,
      limit: sourceGoodsPagination.pageSize,
      page: sourceGoodsPagination.current,
    })
    sourceGoodsTableData.value = res.list
    sourceGoodsPagination.total = res.total
  } catch (error) {
    message.error('加载货品失败')
  } finally {
    sourceGoodsLoading.value = false
  }
}

/**
 * 货品表格分页变化
 */
const handleSourceGoodsTableChange = (pagination: any) => {
  sourceGoodsPagination.current = pagination.current
  sourceGoodsPagination.pageSize = pagination.pageSize
  loadSourceGoods()
}

/**
 * 点击打印预览按钮 - 直接跳转到打印预览
 */
const handleOpenPrintPreview = async (record: any) => {
  if (!selectedTemplate.value) {
    message.warning('请先选择打印模板')
    return
  }

  try {
    const res = await searchGoods({
      goods_no: record.goods_no,
      type: 1,
      att_data: {
        goods_purchase_sn: record.goods_purchase_sn,
        purchase_type_name: record.purchase_type_name,
        purchase_type: record.purchase_type,
        supply_code: record.SupplyCode,
      },
    })

    if (res.count === 1 && res.goods_list && res.goods_list.length > 0) {
      const tempGData = res.goods_list[0]
      const purchasePArr = [9, 10, 13] // 加工类型的采购单
      
      // 构建货品基础信息（不包含尺码）
      const gData: any = {
        color_name: tempGData.color_name || '',
        goods_no: tempGData.goods_no || '',
        unit_price: tempGData.tag_price || '',
        size_id: '', // 稍后在打印预览中选择
        size_name: '', // 稍后在打印预览中选择
        grade: '合格品',
        template_no: tempGData.template?.template_no || '',
        template_name: tempGData.goods_name || '',
        brand_name: tempGData.erp_brand?.title_chinese || '',
        title_english: tempGData.erp_brand?.title_english || '',
        erp_brand: tempGData.erp_brand || '',
        component: '',
        safe_type: tempGData.security_category || '',
        exec_standard: tempGData.exec_standard || '',
        inspector: '08',
        sup_code: tempGData.sup_code || '',
        supply_list: tempGData.supply_list || [],
        goods_purchase_sn: tempGData.att_data.goods_purchase_sn || '',
        purchase_type_name: tempGData.att_data.purchase_type_name || '',
        supply_code: tempGData.att_data.supply_code || '',
        is_process: 0,
        purchase_type: tempGData.att_data.purchase_type || 0,
      }

      // 判断是加工还是成品
      const purchase_type = tempGData.att_data.purchase_type || ''
      if (purchasePArr.includes(Number(purchase_type))) {
        gData.is_process = 1
        gData.component = tempGData.plan_attr?.process_fabric?.value || ''
      } else {
        gData.is_process = 0
        gData.component = tempGData.plan_attr?.fabric?.value || ''
      }

      // 保存尺码列表供打印预览使用
      currentSizeList.value = res.size_list || []
      currentPrintData.value = gData
      
      // 直接打开打印预览
      openPrintPreviewModal()
    } else {
      message.warning('加载货品信息失败')
    }
  } catch (error) {
    message.error('加载货品失败')
  }
}

/**
 * 当前货品的尺码列表
 */
const currentSizeList = ref<any[]>([])

/**
 * 打印预览弹窗
 */
const [PrintPreviewModal, PrintPreviewModalApi] = useVbenModal({
  connectedComponent: PrintPreview,
  onBeforeClose: () => {
    return true
  },
})

/**
 * 打开打印预览窗口
 */
const openPrintPreviewModal = () => {
  if (!selectedTemplate.value) {
    message.warning('请先选择打印模板')
    return
  }

  if (!currentPrintData.value) {
    message.warning('货品数据未加载')
    return
  }

  // 准备打印数据
  const printData = {
    templateType: selectedTemplate.value.key,
    templateName: selectedTemplate.value.name,
    goodsData: currentPrintData.value,
    sizeList: currentSizeList.value,
  }

  // 打开弹窗并传递数据
  PrintPreviewModalApi.setData(printData).open()
}


/**
 * 当前货品数据
 */
const currentPrintData = ref<any>(null)


/**
 * 页面初始化
 */
onMounted(() => {
  // 默认选中第一个模板
  if (printTemplates.length > 0) {
    handleSelectTemplate(printTemplates[0], 0)
  }
  // 加载货品列表
  loadSourceGoods()
})
</script>

<template>
  <div class="print-care-label-page">
    <Row :gutter="20">
      <!-- 左侧：打印模板选择 -->
      <Col :span="5">
        <Card title="打印模板" :bordered="true" class="template-card">
          <div class="template-list">
            <div
              v-for="(template, index) in printTemplates"
              :key="template.key"
              class="template-item"
              :class="{ active: selectedTemplateIndex === index }"
              @click="handleSelectTemplate(template, index)"
            >
              {{ template.name }}
            </div>
          </div>
        </Card>

      </Col>

      <!-- 右侧：货品来源列表 -->
      <Col :span="19">
        <Card :bordered="true">
          <template #title>
            <div class="card-header">
              <span>货品列表</span>
              <span class="ml-2 text-gray-500">
                （当前模板：<span class="text-primary">{{ selectedTemplate?.name || '未选择' }}</span>）
              </span>
            </div>
          </template>

          <!-- 搜索表单 -->
          <Form layout="inline" class="mb-4">
            <FormItem label="采购单号">
              <Input
                v-model:value="searchForm.purchase_sn"
                placeholder="请输入采购单号"
                allow-clear
                style="width: 200px"
                @press-enter="loadSourceGoods"
              />
            </FormItem>
            <FormItem label="货号">
              <Input
                v-model:value="searchForm.goods_no"
                placeholder="请输入货号"
                allow-clear
                style="width: 180px"
                @press-enter="loadSourceGoods"
              />
            </FormItem>
            <FormItem label="简码">
              <Input
                v-model:value="searchForm.template_no"
                placeholder="请输入简码"
                allow-clear
                style="width: 180px"
                @press-enter="loadSourceGoods"
              />
            </FormItem>
            <FormItem>
              <Button type="primary" @click="loadSourceGoods">
                <AntPlusOutlined />
                查询
              </Button>
            </FormItem>
          </Form>

          <!-- 货品源表格 -->
          <Table
            :columns="sourceGoodsColumns"
            :data-source="sourceGoodsTableData"
            :loading="sourceGoodsLoading"
            :pagination="sourceGoodsPagination"
            :scroll="{ x: 1200, y: 'calc(100vh - 450px)' }"
            bordered
            size="small"
            @change="handleSourceGoodsTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'template_images'">
                <img
                  v-if="record.template_images && record.template_images.length > 0"
                  :src="record.template_images[0]"
                  :alt="record.goods_name"
                  style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px"
                />
              </template>
              <template v-if="column.key === 'action'">
                <Button type="primary" size="small" @click="handleOpenPrintPreview(record)">
                  <AntPrinterOutlined />
                  打印预览
                </Button>
              </template>
            </template>
          </Table>
        </Card>
      </Col>
    </Row>

    <!-- 打印预览弹窗 -->
    <PrintPreviewModal />
  </div>
</template>

<style scoped lang="scss">
.print-care-label-page {
  height: 100vh;
  padding: 16px;
  overflow: auto;
  background-color: #f5f5f5;

  .template-list {
    .template-item {
      padding: 12px 16px;
      margin-bottom: 8px;
      font-size: 14px;
      cursor: pointer;
      background-color: #fff;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        color: #1890ff;
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgb(0 0 0 / 9%);
      }

      &.active {
        font-weight: 600;
        color: #1890ff;
        background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgb(24 144 255 / 20%);
      }
    }
  }

  .template-card {
    position: sticky;
    top: 16px;
  }

  .multiple-size-selection {
    padding: 16px 0;

    .text-gray-600 {
      color: #666;
    }
  }

  .card-header {
    width: 100%;
  }

  .text-primary {
    font-weight: 500;
    color: #1890ff;
  }

  .text-gray-500 {
    font-size: 13px;
    color: #999;
  }

  // 优化表格样式
  :deep(.ant-table) {
    font-size: 13px;

    .ant-table-thead > tr > th {
      font-weight: 600;
      background-color: #fafafa;
    }

    .ant-table-tbody > tr:hover > td {
      background-color: #e6f7ff;
    }
  }

  // 优化按钮间距
  :deep(.ant-btn) {
    &.ml-2 {
      margin-left: 8px;
    }

    &.mr-2 {
      margin-right: 8px;
    }
  }

  // 优化输入框样式
  :deep(.ant-input),
  :deep(.ant-input-textarea) {
    border-radius: 4px;
  }

  // 优化卡片样式
  :deep(.ant-card) {
    border-radius: 8px;
    box-shadow: 0 1px 2px rgb(0 0 0 / 3%);
  }
}
</style>

